<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 后台操作公共控制器
 *
 * 包含常用数据库操作和权限验证
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */
class SDF_Controller extends CI_Controller{
	protected $M = '';//当前访问的方法名
    protected $C = '';//当前访问的类名
    protected $D = '';//当前访问的模块名
    protected $table_name = '';//默认操作表名，可在子类中修改
    protected $model_name = '';//默认模型名，可在子类中修改
    protected $data = array();//输入到模板的数组
    protected $admin_user = array();//后台用户信息
    protected $soft_id = 0;//当前操作的软件id
	public function __construct()	{
        parent::__construct();
        $this->_load_helper();
        //$this->output->enable_profiler(TRUE);//输出调试信息
        $this->output->set_header('Content-Type: text/html; charset=UTF-8');
        $this->data['soft_id'] = $this->soft_id = $this->input->cookie('soft_id')?$this->input->cookie('soft_id'):0;
        $this->C = $this->table_name = $this->router->fetch_class();
        $this->M = $this->router->fetch_method();
        $this->D = $this->router->fetch_directory();
        #如果没有设置模型名字
        if(empty($this->model_name))$this->model_name = $this->D.$this->C.'_model';
        define('__URL__', base_url($this->D.$this->C));//模型位置初始化

        $token = $this->input->cookie('token');
        $this->load->library('Auth');
        $this->data['admin_user'] = $this->admin_user = Auth::get_admin_user_by_token($token);
        if(is_array($this->admin_user)){//如果已登录
            if(!(Auth::is_administrator($this->admin_user['username'])) and $this->check_auth()===false ){//权限不足
                $this->_error('没有权限');
            }
        }else{//登录超时，或者没有登录
            if(IS_AJAX){//如果是ajax，返回状态码，否则重定向到登陆页。
                //$this->_error('没有登录，或者登录超时！');
                show_error('登录已超时！',301,'操作失败!');
                return false;
            }
            redirect(site_url('login'), 'refresh');
        }
        $this->_write_log();//写日志
    }

    /**
     * 写日志
     */
    private function _write_log(){
        $this->load->model('admin/admin_log_model');
        $modules = str_replace('/','',$this->D);
        $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
        $log_info = array(
            'user_id'=> 1,
            'modules'=> $modules,
            'controller'=> $this->C,
            'method'=> $this->M,
            'log_info'=> json_encode($_REQUEST),
            'ip_address'=> $this->input->ip_address(),
            'url'=> $url,
            'user'=>$this->admin_user['username'],
            'create_time'=> time()
        );
        $this->admin_log_model->_write_log($log_info);
    }

    /**
     * 加载公共辅材函数
     */
    private function _load_helper(){
        $this->load->helper('url');
        $this->load->helper('form');
    }

    /**
     * 验证用户权限
     * @return bool
     */
    private function check_auth(){
        $this->load->model('admin/admin_user_model');
        $admin_user_auth = $this->admin_user_model->get_admin_user_auth($this->admin_user['id'],$this->soft_id,true);//获取用户权限列表（使用权限缓存数据，如果有的话）
        $admin_user_key = $this->D.$this->C.'/'.$this->M;
        if(!empty($admin_user_key) and isset($admin_user_auth[$admin_user_key]) or Auth::is_administrator($this->admin_user['username'])){
            return true;
        }
        return false;
    }
    /**
     * 重构方法调用模式
     * @param $method
     * @param $rsegments
     * @return bool
     */
    public function _remap($method,$rsegments){
        if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($this)))){
            $this->_error('你请求的操作"'.$method.'"不存在！');return false;
        }
        call_user_func_array(array(&$this, $method), $rsegments);
    }

    /**
     * 快接输出错误提示
     * @param $message
     * @param string $title
     */
    protected function _error($message,$title='操作失败!'){
        show_error($message,300,$title);
    }

    /**
     * 快接输出成功提示
     * @param $message
     * @param string $title
     */
    protected function _success($message,$title='操作成功!'){
        show_error($message,200,$title);
    }

    /**
     * 默认列表
     */
    public function index(){
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        /*echo current_url();exit;
        echo $product_id = $this->uri->ruri_string();
        echo site_url($this->uri->ruri_string());exit;
        echo $product_id;exit;*/
        $this->data['list'] = $this->_list();//数据列表
        $this->load->view($this->D.$this->C.'/'.$this->M,$this->data);
    }

    /**
     * 添加页面
     */
    public function add(){
        $this->load->view($this->D.$this->C.'/'.$this->M,$this->data);
    }

    /**
     * 插入数据
     */
    public function insert(){
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        $data = $this->input->post('DATA');
        $id = $this->Model->_insert($data);
        if(empty($id)){
            $this->_error('添加失败！');
        }
        $this->_success('添加成功！');
    }

    /**
     * 编辑页面
     */
    public function edit($id){
        if(!is_numeric($id)){
            $this->_error('编辑的id不是一个整数。');return false;
        }
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        $_REQUEST['PK'] = $this->Model->_get_pk();
        $row = $this->Model->_row(array($_REQUEST['PK']=>$id));
        $this->data['DATA'] = $row;
        $this->load->view($this->D.$this->C.'/'.$this->M,$this->data);
    }

    /**
     * 更新数据
     */
    public function update(){
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        $pk = $this->Model->_get_pk();
        $pk_v = $this->input->post($pk);
        if(!is_numeric($pk_v)){
            $this->_error('更新的id不是一个整数。');return false;
        }
        $where=array($pk=>$pk_v);
        $data = $this->input->post('DATA');
        //print_r($where);print_r($data);exit;
        $affected_rows = $this->Model->_update($where,$data);
        $this->_success('成功修改条【'.$affected_rows.'】数据！');
    }

    /**
     * 字段设置
     */
    public function setField(){
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        $pk = $this->Model->_get_pk();

        $value = $this->input->get_post('value');
        $name = $this->input->get_post('name');

        $where=array($pk=>$this->input->get_post('id'));
        $data = array(
            $name=>$value
        );
        //print_r($where);print_r($data);exit;
        $affected_rows = $this->Model->_update($where,$data);
        if($affected_rows === false){
            log_message('debug','更新失败'.$this->Model->db->last_query());
            $this->_error('更新失败'.$this->Model->db->last_query());
        }else{
            $this->_success('成功修改条【'.$affected_rows.'】数据！');
        }
    }

    /**
     * 删除数据
     * @param $ids
     */
    public function delete($ids){
        $this->load->model($this->model_name,"Model");
        $this->Model->_from($this->table_name);
        $list_fields = $this->Model->_list_fields();
        $affected_rows = $this->Model->_delete(array($list_fields[0]=>$ids));
        $this->_success('成功，影响到行数为：'.$affected_rows);
    }

    /**
     * 获取数据列表
     * @return mixed
     */
    protected  function _list(){
        $map = $this->_search();//生成查询map
        if (method_exists ( $this, '_filter' )) {
            $map = $this->_filter($map);//对查询map加工处理
        }
        $_POST['pageNum'] = intval($this->input->get_post('pageNum'))>0?intval($this->input->get_post('pageNum')):1; //<!--【必须】value=1可以写死-->
        $_POST['numPerPage'] = intval($this->input->get_post('numPerPage'))>0?intval($this->input->get_post('numPerPage')):20;//<!--【可选】每页显示多少条-->
        $_POST['orderField'] = $this->input->get_post('orderField')?$this->input->get_post('orderField'):$this->Model->_get_pk();//<!--【可选】查询排序字段-->
        $_POST['orderDirection'] = in_array($this->input->get_post('orderDirection'),array('desc','asc'))?$this->input->get_post('orderDirection'):'desc';//<!--【可选】升序降序-->

        $list = $this->Model->_map($map)->_limit($_POST['numPerPage'],($_POST['pageNum']-1)*$_POST['numPerPage'])->_order_by($_POST['orderField'],$_POST['orderDirection'])->_list();
        #echo $this->Model->db->last_query();
        $_POST['totalCount'] = $this->Model->_map($map)->_from($this->table_name)->_count();//总共多少条【服务器获取返回】
        return $list;
    }

    /**
     * 加工搜索条件 这个方法用于实现复杂的搜索，必须被实现
     * @param $map
     * @return mixed
     */
    //abstract protected function _filter($map);
    protected function _filter($map){
        /*$keywords = $this->input->get_post('keywords');
        if(!empty($keywords)){
            $map['like']=array('username'=>$keywords);
        }*/
        return $map;
    }
    /**
     * 生成查询map
     * @return array
     */
    protected function _search() {
        $map = array();
        $list_fields = $this->Model->_list_fields();
        foreach ($list_fields as $key ) {
            $val = $this->input->get_post($key);#有参数，切不为'all'时
            if ($val !== FALSE and strtoupper($val) !== ''){
                $map['where'][$key] = $val;
            }
        }
        return $map;
    }
    /*public function _field_data(){
        return $this->Model->db->field_data($this->C);
    }*/
}


// END Controller class

/* End of file Controller.php */
/* Location: ./system/core/Controller.php */